<?php

namespace App\Http\Controllers;

use App\Http\Repositories\UserManage\UserRepo;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Symfony\Component\HttpFoundation\Response;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    protected $validator;
    protected $self_repo;

    const VALIDATOR = null;

    public function getValidator()
    {
        return call_user_func(static::VALIDATOR . '::newInstance');
    }

    public function returnResponse($data, $status = 200, $msg = '', $header = [])
    {
        $data = [
            'data' => $data,
            'status' => $status,
            'msg' => $msg,
        ];
        return response()->json($data, $status, $header);
    }

    public function getUser()
    {
        return Auth::user();
    }

    public function getUserId()
    {
        return Auth::id();
    }

    /**
     * 登录
     */
    public function login(array $params)
    {
        // !empty($user_args['password']) && $user_args['password'] = Hash::make($user_args['password']);
        if (!Auth::attempt(['phone' => ($params['phone'] ?? ''), 'password' => ($params['password'] ?? '')])) {
            return response(["msg" => "Bad Credential"], Response::HTTP_UNAUTHORIZED);
        }
        $token = Auth::user()->createToken(($params['phone'] ?? ''))->plainTextToken;
        $cookie = cookie('token', $token, 60 * 24);

        return response(['token' => $token])->withCookie($cookie);
    }

    public function createTokenByOpenid($openid)
    {
        $user = app(UserRepo::class)->query()->where("openid", $openid)->first();
        $user->tokens()->delete();
        $token = $user->createToken($openid)->plainTextToken;

        Auth::login($user);

        return ["token" => $token];
    }
    /**
     * 登出
     */
    public function logout()
    {
        Auth::user()->currentAccessToken()->delete();

        $cookie = Cookie::forget("token");

        return response(['msg' => 'Success'])->withCookie($cookie);
    }

    public function my_validate($input, $rule_name, $message_name = 'messages', $attribute_name = 'attributes')
    {
        $validator = $this->getValidator();
        $is_validate = $validator->validate($input, $validator->$rule_name(), $validator->$message_name(), $validator->$attribute_name());

        return $is_validate;
    }
}
